package com.apply.config.web;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

/**
 * 跨域拦截器
 *
 * @author tianp
 */
public class CORSInterceptor extends HandlerInterceptorAdapter {
    private List<String> defaultAccessAllowedFrom;

    public CORSInterceptor(List<String> defaultAccessAllowedFrom) {
        this.defaultAccessAllowedFrom = defaultAccessAllowedFrom;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String origin = request.getHeader("Origin");
        if (StringUtils.isEmpty(origin)) {
            return true;
        } else {
            URL u = new URL(origin);
            String host = u.getHost().toLowerCase();
            Iterator var7 = this.defaultAccessAllowedFrom.iterator();

            while (var7.hasNext()) {
                String s = (String) var7.next();
                if (host.matches(s)) {
                    response.setHeader("Access-Control-Allow-Origin", "*");
                    response.setHeader("Access-Control-Allow-Headers", "sid,Content-Type,Access-Token,X-Requested-With");
                    response.setHeader("Access-Control-Request-Headers", "PUT,POST,GET,DELETE,OPTIONS");
                    break;
                }
            }
            return !"options".equalsIgnoreCase(request.getMethod());
        }
    }
}